class List {
    constructor() {
        //显示名字
        this.getData()
        //显示购物车数量
        this.shopNum()
        //获取数据，
        this.getDate()
        this.bindEve()
    }
    //绑定事件
    bindEve = () => {
        //遍历li绑定点击事件
        this.$('.sk_list ul li').forEach((li, index) => {
            // console.log(li);
            li.addEventListener('click', this.liClick.bind(this, index))
        })
        //事件委托给父元素
        this.$('.sk_list ul').addEventListener('click', this.dispach)
        // 先转换为数组 
        this.$('.sk_page .page_num a').forEach((v, index) => {
            v.addEventListener('click', this.aClick.bind(this, index))
        })
        //确定跳转页面
        this.$('#sure').addEventListener('click', this.skipPage)
        //点击关闭广告
        this.$('.close-btn').addEventListener('click', this.closeAd)
        //搜索点击事件
        this.$('.form button').addEventListener('click', this.search.bind(this))
        //升序  降序
        this.$('.up').addEventListener('click', this.upOrder.bind(this))
        this.$('.down').addEventListener('click', this.downOrder.bind(this))
        //给商品父元素绑定点击事件  事件委托
        this.$('.ulFirst').addEventListener('click', this.dispach)

    }
    //分派  
    dispach = (eve) => {
        let ele = eve.target
        // console.log(ele.nodeName);
        if (ele.nodeName == "IMG") {
            //把商品id存下来
            localStorage.setItem("goodsId", ele.dataset.id)
        }

    }
    //升序降序
    sortMethod = ""
    flag = true
    //属性判断是否需要价格排序
    isPriceOrder = true
    upOrder() {
        this.flag = false
        this.isPriceOrder = false
        this.sortMethod = "sortMethod=ASC&"
        this.getDate()
    }
    //降序
    downOrder() {
        this.sortMethod = "sortMethod=DESC&"
        this.isPriceOrder = false
        this.flag = false
        this.getDate()
    }
    //关键词搜索
    searchValue = ""
    async search() {

        this.flag = false
        this.searchValue = `search=${text.value}&`
        if (text.value.trim() == "") {
            layer.msg('请输入关键词.....');
            return
        }


        let { data, status } = await axios.get("http://localhost:8888/goods/list?search=" + text.value)
        if (data.code == 1 && status == 200) {
            //渲染页面
            let html = ""
            data.list.forEach((date, k) => {
                html += `<li class="sk_goods">
           <a href="detail.html"><img src=${date.img_big_logo} alt=""></a>
           <h5 class="sk_goods_title">${date.title}
           <p class="sk_goods_price"><em>${date.current_price}</em> <del>${date.price}</del></p>
           <div class="sk_goods_progress">
           已售<i>${date.sale_type}</i>
           <div class="bar">
               <div class="bar_in"></div>
           </div>
           剩余<em>${date.goods_number}</em>件
       </div>
       <a href="#none" class="sk_goods_buy" onclick=List.nowBuy(${date.goods_id})>立即抢购</a>
   </li>
       `

            })
            this.$('.ulFirst').innerHTML = html
        } else {
            layer.msg('网络请求失败.....');
        }

    }
    //关闭广告
    closeAd = () => {
        this.$('.mobile img').style.display = "none"
        this.$('.close-btn').style.display = "none"
    }
    //显示购物车商品数量
    shopNum() {
        axios.defaults.headers.common['Authorization'] = localStorage.getItem("token")
        axios.get("http://localhost:8888/cart/list/?id=" + localStorage.getItem('user_id')).then(res => {
            let { data, status } = res
            // console.log(data);
            let num = 0
            if (status == 200 && data.code == 1) {

                data.cart.map(v => {

                    return num += v.cart_number
                })
                // console.log(this);
                this.$('.count').innerHTML = num
            }
        })

    }
    //发送请求 获取数据 修改名字
    async getData() {
        // console.log(this);
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        axios.defaults.headers.common['Authorization'] = localStorage.getItem("token")
        let res = await axios.get("http://localhost:8888/users/info?id=" + localStorage.getItem("user_id"))

        let { data, status } = res
        // console.log(data.info.nickname, this);
        if (status == 200 && data.code == 1) {
            this.$('.nav').firstElementChild.firstElementChild.innerHTML = "您好，尊敬的" + data.info.nickname

        }

    }
    //输入页数  跳转
    skipPage = () => {
        let pageNum = this.$('.page_skip input').value - 0
        this.num = pageNum
        // console.log(this.num, pageNum);
        if (!pageNum || pageNum < 0) {
            layer.msg('请输入跳转的页数.......');
            return
        }

        if (pageNum > 77) {
            pageNum = 77
            // this.$('.sk_page .page_num .current').className = "common"
            // this.$('.sk_page .page_num a')[5].className = "common current"

        }
        this.getDate(pageNum)
    }
    //页数点击事件
    num = 1
    nums = 1
    aClick = (index, eve) => {
        let tar = eve.target

        //1 2 3 4 5
        if (tar.classList.contains("common")) {
            //取消类名
            this.$('.sk_page .page_num .current').className = "common"
            // 增加类名
            this.$('.sk_page .page_num a')[index].className = "common current"

            this.num = index
            this.nums = index

            if (this.flag == false) {
                this.getDate(index, "sortType=price&")
            } else {
                this.getDate(index)
            }
        }

        //上一页
        if (tar.classList.contains("pn-prev")) {

            // console.log(this.nums);
            //取消类名
            this.$('.sk_page .page_num .current').className = "common"
            if (this.nums == 1) {
                this.nums = 2

            }
            // 增加类名
            this.$('.sk_page .page_num a')[--this.nums].className = "common current"
            if (this.num == 1) {
                this.num = 2
                layer.msg('亲，当前已经是第一页了');
            }
            this.num--
            this.getDate(this.num)
        }
        //下一页
        if (tar.classList.contains("pn-next")) {

            //取消类名
            // console.log(this.nums);
            this.$('.sk_page .page_num .current').className = "common"
            //7
            // console.log(this.nums);
            this.num++
            //只有77页
            if (this.num == 78) {
                this.num = 77
                layer.msg('亲，当前已经是最后一页了');
            }

            //1 2 3 4 5类名
            if (this.nums < 6) {
                this.$('.sk_page .page_num a')[++this.nums].className = "common current"
            } else {
                this.$('.sk_page .page_num a')[6].className = "common current"
            }



            //判断flag 确定是不是价格排序
            if (this.isPriceOrder == false) {
                this.getDate(this.num, "sortType=price&")
            } else {
                this.getDate(this.num)
            }


        }

    }
    // li绑定点击事件
    liClick = (index) => {
        //取消类名
        this.$('.sk_list ul .current').className = ""
        // 
        this.$('.sk_bd .ulFirst').className = ""
        // //添加类名
        this.$('.sk_list ul li')[index].className = "current"
        this.$('.sk_bd ul')[index].className = "ulFirst"

        this.getDate(++index)
    }
    //获取数据
    async getDate(num = 1, str = "") {
        // console.log(this.seach);
        //str 为 true  价格排序
        str = this.isPriceOrder == false ? "sortType=price&" : ""
        //价格的升序 倒序
        // this.sortMethod = this.sortMethod == "sortMethod=DESC&" ? "sortMethod=DESC&" : "sortMethod=ASC&"

        if (this.sortMethod == "sortMethod=DESC&") {
            this.sortMethod == "sortMethod=DESC&"
        } else if (this.sortMethod == "sortMethod=ASC&") {
            this.sortMethod == "sortMethod=ASC&"
        } else {
            this.sortMethod == ""
        }


        //搜索内容
        this.searchValue = this.searchValue == false ? `` : `search=${text.value}&`
        let res = await axios(`http://localhost:8888/goods/list?${str}${this.sortMethod}${this.searchValue}current=` + num)

        // console.log(res);
        //获取数据 还有状态码
        let { data, status } = res

        if (!status == 200) return;

        let html = ""

        data.list.forEach(date => {
            // console.log(date);   ${date.img_big_logo}
            html += `<li class="sk_goods"> 
                            <a href="detail.html"><img src=${date.img_big_logo} data-id=${date.goods_id}></a>
                            <h5 class="sk_goods_title">${date.title}
                            <p class="sk_goods_price"><em>${date.current_price}</em> <del>${date.price}</del></p>
                            <div class="sk_goods_progress">
                            已售<i>${date.sale_type}</i>
                            <div class="bar">
                                <div class="bar_in"></div>
                            </div>
                            剩余<em>${date.goods_number}</em>件
                        </div>
                        <a href="javascript:void(0);" class="sk_goods_buy" onclick=List.nowBuy(${date.goods_id})>立即抢购</a>
                       </li>
                     `
        });
        this.$(".sk_bd .ulFirst").innerHTML = html
    }
    //立即去购买
    static nowBuy(good_id) {


        let token = localStorage.getItem("token");
        // console.log(token);
        if (!token) location.href = './login.html?returnUrl=./list.html'
        //加入购物车需要用户id 和  商品id
        let userId = localStorage.getItem("user_id")
        let parm = `id=${userId}&goodsId=${good_id}`
        // console.log(parm);

        //设置请求头信息
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

        axios.defaults.headers.common['Authorization'] = token;

        axios.post("http://localhost:8888/cart/add", parm).then(res => {

            // console.log(res);
            let { data, status } = res;
            if (!status == 200) return;
            // console.log(data);
            if (data.code == 0) location.href = './login.html?returnUrl=./list.html'

            //弹出提示框
            layer.confirm('是否去购物车结算', {
                btn: ['是', '继续买'] //按钮


            }, function () {
                // 去购物车
                location.href = './cart.html';
            }, function () {
                //继续买


            });


        })
    }
    //封装个获取节点的方法
    $(ele) {
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res
    }
}
new List()
